const axios = require('axios')
axios.default.withCredentials = true
// '/api' 设置代理 专用
const baseUrl = process.env.NODE_ENV === 'development' ? '/api' : ''
// 服务器返回状态码枚举
const responseStatusEnum = {
    222: '单据状态不符',
    400: '请求出错',
    401: '授权失败，请重新登录',
    403: '拒绝访问',
    404: '请求错误,未找到该资源',
    451: '服务端错误',
    500: '服务端错误'
}
axios.interceptors.response.use(
    response => {
        if (response.data.code != '200') {
            console.log(response.data.msg || '未知错误')
        }
        return response.data
    },
    error => {
        if (error.message && error.message === 'timeout of 10000ms exceeded') {
            return Promise.reject(error)
        } else {
            let {
                status,
                data: { msg }
            } = error.response
            console.log(msg || responseStatusEnum[status])
            return Promise.reject(error)
        }
    }
)

export const baseRequest = axios.create({
    baseURL: baseUrl,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
    validateStatus(status) {
        responseStatusEnum[status] && console.log(responseStatusEnum[status])
        return (status >= 200 && status < 300) || status == 451
    }
})

// mock请求时，不需要设置baseURL，headers等
export const mockRequest = axios
